package org.goyo.main.domain.dao.storage.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.goyo.common.exception.DBException;
import org.goyo.common.utils.Pager;
import org.goyo.common.utils.ToolUtils;
import org.goyo.main.domain.dao.BaseDAO;
import org.goyo.main.domain.dao.storage.ISaleOutStorageDao;
import org.goyo.main.domain.entity.storage.SaleOutStorageEntry;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;
@Repository
public class SaleOutStorageDaoImpl extends BaseDAO implements ISaleOutStorageDao{

	@Override
	public Pager findByCond(String cond, Pager pager,Object[] groupUuids) throws DBException {
		StringBuffer buf = new StringBuffer("from SaleOutStorage where 1=1 ");
		buf.append(" and depGroup in ");
		buf.append(ToolUtils.getInParamter(groupUuids));
		
		if (StringUtils.isNotBlank(cond)) {
		  buf.append(" and ");
          buf.append(cond);
		}
	    String hql = this.addSort(buf, pager);
	    String countHql = "select count(*) "+buf.toString();
		return this.findObjectsByPager(hql,countHql, pager);
	}

	@Override
	public List<SaleOutStorageEntry> findByParentId(String parentId) throws DBException {
		String hql = "from SaleOutStorageEntry where parentId=?";
		return this.findObjects(hql, null, new Object[]{parentId});
	}
	
	@Override
	public double getSumQty(String materialId,String bizType) throws DBException {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT IFNULL(SUM(t.out_storage_qty),0) FROM t_sale_out_storage_entry t,t_sale_out_storage t1");
		sql.append(" WHERE t.parent_id = t1.uuid AND t1.biz_type =? AND  t.materialId =?");
		SQLQuery query = this.getSession().createSQLQuery(sql.toString());
		query.setParameter(0, bizType);
		query.setParameter(1, materialId);
		List list = query.list();
		return Double.valueOf(list.get(0).toString());
	}
}
